<script setup>
import { getCategoryListApi } from '@/api/category'
import { addSpuApi, updateSpuApi } from '@/api/spu'
import { getSupplierPageApi } from '@/api/supplier'
import { getCurrentInstance, onMounted, ref } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'

const brandList = ref([
  {id:1,name:'华为'},
  {id:2,name:'小米'},
  {id:3,name:'苹果'},
])
const supplierList = ref([])
const categoryList = ref([])
const value = ref([])
//获取当前Vue实例
const instance = getCurrentInstance()
const ruleFormRef = ref(null)
const dialogFormVisible = ref(false)
const title = ref('')
const spuList = ref({
    id: null,
    title: null,
    subTitle: null,
    categoryId3: null,
    description: null,
    content: null,
    brandId: null,
    supplierId: null,
    children : [],
})


const removeChildren  = (index) => {
    spuList.value.children .splice(index, 1)
}
const add = () => {
    spuList.value.children .push({
      price:null,
      realPrice:null,
      code:null,
      unit:null,
      productWeight:null,
      productLength:null,
      productWidth:null,
      productHeight:null,
    })
}
const reset = () => {
    spuList.value = {
        id: null,
        title: null,
        subTitle: null,
        categoryId3: null,
        description: null,
        content: null,
        brandId: null,
        supplierId: null,
        children : [],
    }
}

const save =async () => {
     if (!ruleFormRef) return
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            let res = null
            if (spuList.value.id) {
                res = await updateSpuApi(spuList.value)
            }else {
                res = await addSpuApi(spuList.value)
            }
            if (res.code == 1) {
                ElMessage.success('操作成功')
                dialogFormVisible.value = false
                instance.emit('refresh')
            }else{
                ElMessage.error('操作失败')
            }
        } else {
        console.log('error submit!', fields)
        }
    })
}

const handleChange = (val) => {
    // 将级联选择器的值赋给 supplierForm.pcdId
    // val 是一个数组，通常取最后一个值作为选中的ID
    spuList.value.categoryId3 = val[val.length - 1]
}

const rules = ref({
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' }
  ],
})

const getCategoryList = async () => {
    let res = await getCategoryListApi()
    categoryList.value = res.data
}

const getsupplierList = async () => {
    let res = await getSupplierPageApi()
    supplierList.value = res.data
}
defineExpose({
    dialogFormVisible,
    title,
    spuList,
    reset,
})

onMounted(()=>{
    getCategoryList()
    getsupplierList()
})
</script>

<template>
    <el-dialog v-model="dialogFormVisible" :title="title">
    <el-form :model="spuList" :rules="rules" ref="ruleFormRef" label-width="auto">

      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标题" placeholder="请输入标题" prop="title" >
            <el-input v-model="spuList.title" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="副标题" placeholder="请输入副标题" prop="subTitle" >
            <el-input v-model="spuList.subTitle" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属分类" placeholder="请选择"  >
            <el-cascader style="width: 100%;" v-model="value" :options="categoryList" @change="handleChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品描述" placeholder="请输入商品描述" prop="description" >
            <el-input v-model="spuList.description" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="供应商"  prop="supplierId" >
            <el-select v-model="spuList.supplierId" placeholder="请选择供应商">
                <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.supplierName" >
                  {{ item.supplierName }}
                </el-option> 
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌"  prop="brandId" >
            <el-select v-model="spuList.brandId" placeholder="请选择品牌">
                <el-option v-for="item in brandList" :key="item.id" :value="item.id" :label="item.name" >
                  {{ item.name }}
                </el-option> 
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="商品描述内容">
        <div class="editor">
        <QuillEditor
          v-model:content="spuList.content"
          contentType="html"
          theme="snow"
          :toolbar="[
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'script': 'sub'}, { 'script': 'super' }],
            [{ 'indent': '-1'}, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean'],
            ['link', 'image', 'video']
          ]"
          class="rich-text-editor"
        />
        </div>
      </el-form-item>
        </el-col>
      </el-row>
      <el-button type="primary" @click="add">新增商品规格</el-button>

      <!-- 第五行 -->
       <el-row :gutter="20" v-for="(s,index) in spuList.children " :key="index">
        <el-col :span="8">
          <el-form-item label="单价">
            <el-input v-model="s.price" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="真实单价">
            <el-input v-model="s.realPrice" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品条码">
            <el-input v-model="s.code" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品单位">
            <el-input v-model="s.unit" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品重量">
            <el-input v-model="s.productWeight" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品长度">
            <el-input v-model="s.productLength" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品宽度">
            <el-input v-model="s.productWidth" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品高度">
            <el-input v-model="s.productHeight" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="">
            <el-button type="danger" @click="removeChildren (index)">删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.editor{
  padding: 20px;
  border-radius: 8px;
}
.rich-text-editor {
  height: 400px;
  width: 100%;
  max-width: 800px;
}


:deep(.ql-toolbar) {
  border-radius: 4px 4px 0 0;
  border-color: #dcdfe6;
}


:deep(.ql-container) {
  border-radius: 0 0 4px 4px;
  border-color: #dcdfe6;
}


:deep(.ql-editor) {
  min-height: 200px;
}
</style>